package com.ym.b2b.order.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ym.b2b.commons.conf.B2BConstants;
import com.ym.b2b.commons.conf.WebTokenUser;
import com.ym.b2b.commons.controller.BaseController;
import com.ym.b2b.order.service.EmSOrderService;
import com.ym.b2b.order.sqlbean.EmSOrder;
import com.ym.b2b.order.sqlbean.EmSShoppingCart;
import com.ym.b2b.order.vo.OrderInfoVO;
import com.zc.commons.base.Page;
import com.zc.commons.base.Result;
import com.zc.export.ExcelUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/trade")
public class OrderController extends BaseController {

    @Autowired
    private EmSOrderService orderService;
    
    private Logger          logger = Logger.getLogger(getClass());

    /**
     * 前台订单列表
     * @Title: searchOrder
     * @Param @param emSOrder
     */
    @RequestMapping("searchOrder.s")
    public String searchOrder(EmSOrder emSOrder, Page<EmSOrder> page, HttpServletRequest req) {
        try {
            page.setPageable("true");
            page.setPageUrl(req);
            orderService.searchPageOrders(emSOrder, page);
            req.setAttribute("order", page);
            req.setAttribute("pageUrl", page.getPageUrl());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "support/order/s_order_list";
    }

    @RequestMapping("searchHello.s")
    public String searchHello(EmSOrder emSOrder, Page<EmSOrder> page, HttpServletRequest req) {
        try {
            System.exit(-1);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "support/order/s_order_list";
    }
    /**
     * 订单分页列表
     * @Title: searchPageOrder
     * @Throws
     */

    @RequestMapping("searchPageOrder.s")
    @ResponseBody
    public Result searchPageOrder(EmSOrder emSOrder, Page<EmSOrder> page, HttpServletRequest req) {
        Result result = new Result();
        try {
            WebTokenUser tokenUser = getWebTokenUser(req);
            if (tokenUser != null) {
                emSOrder.setBuyerCode(tokenUser.getBuyerCode());
            }
            page = orderService.searchPageOrders(emSOrder, page);
            result.setResultPage(page);
        } catch (Exception e) {
            result.setCodeResult(Result.CODE_100, e.getMessage());
        }
        return result;
    }

    /**
     * 订单详情
     * @Title: searchOrderDetail
     * @Throws
     */
    @RequestMapping("getOrderDetail.s")
    @ResponseBody
    public Result showOrderDetail(OrderInfoVO vo, HttpServletRequest req, HttpServletResponse res) {
        Result ret = new Result();
        try {

            WebTokenUser tokenUser = getWebTokenUser(req);
            if (tokenUser != null) {
                vo.setUser(tokenUser);
            }
            ret = orderService.searchOrderDetail(vo);

            // res.getWriter().print(JSON.toJSONString(ret));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, e.getMessage());
        }

        return ret;
    }

    /**
     * @Title: searchOrderExcel
     * @Description: excel 导出
     * @Throws
     */
    @RequestMapping("searchOrderExcel.s")
    @ResponseBody
    public Result searchOrderExcel(EmSOrder emSOrder, Page<EmSOrder> page, HttpServletRequest req) {

        Result result = new Result();
        try {
            page.setPageable("true");
            page.setPageUrl(req);
            orderService.searchPageOrders(emSOrder, page);

            result.setResultPage(page);
            result.putData("svo", emSOrder);

            ExcelUtil<EmSOrder> excelUtil = new ExcelUtil<EmSOrder>();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("model", page.getRows());
            result = excelUtil.createExcel("orderList", map);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 购物车点击提交订单按钮, 确认信息 显示
     * 
     * @Title: getInfoForOrder
     */
    @RequestMapping(value = "getInfoForOrder.s")
    public ModelAndView getInfoForOrder(OrderInfoVO orderInfo, HttpServletRequest req) {
        ModelAndView m = new ModelAndView();
        Result ret = new Result();
        try {
            WebTokenUser tokenUser = getWebTokenUser(req);
            orderInfo.setUser(tokenUser);

            List<EmSShoppingCart> shoppingCarts=new ArrayList<>();
            //选中购物车商品
            String productCodes=req.getParameter("codes");
            this.putShoppingCarts(shoppingCarts,productCodes);
            orderInfo.setShoppingCartList(shoppingCarts);

            ret = orderService.getInfoForOrder(orderInfo);
            Map<String,Object> data=ret.getData();
            data.put("codes",productCodes);
            ret.setData(data);
            m.addObject("ret", ret);
            if (ret.getCode().equals(Result.CODE_100)) {
                m.setViewName("forward:/views/jsp/center/trade/shoppingcart/c_shopping_cart_list.jsp");
                return m;
            }
            m.setViewName("center/trade/order/c_shoppingcart_for_order");
        } catch (Exception e) {
            e.printStackTrace();
            ret.setCodeResult(Result.CODE_100, e.getMessage());
            m.addObject("ret", ret);
            m.setViewName("forward:/views/jsp/center/trade/shoppingcart/c_shopping_cart_list.jsp");

        }
        return m;
    }

    /**
     * 选中购物车商品
     * @param shoppingCarts
     * @param productCodes
     */
    private void putShoppingCarts(List<EmSShoppingCart> shoppingCarts,String productCodes){
        //选中购物车商品productCode
        JSONObject jso = JSONObject.fromObject(productCodes);
        Iterator it = jso.keys();
        while (it.hasNext()) {
            String key = (String) it.next();
            String productCode = jso.getString(key);
            EmSShoppingCart emSShoppingCart=new EmSShoppingCart();
            emSShoppingCart.setProductCode(productCode);
            shoppingCarts.add(emSShoppingCart);
        }

    }

    /**
     * 下单接口 *****重要******
     * 
     * @Title: generateOrder
     */
    @RequestMapping(value = "generateOrder.s")
    public ModelAndView generateOrder(OrderInfoVO orderInfo, HttpServletRequest req) {

        ModelAndView m = new ModelAndView();
        Result ret = new Result();
        try {
            WebTokenUser tokenUser = getWebTokenUser(req);
            if (tokenUser == null) {
                m.setViewName(B2BConstants.WEB_NOT_LOGIN);
                return m;
            }
            orderInfo.setUser(tokenUser);

            List<EmSShoppingCart> shoppingCarts=new ArrayList<>();
            //选中购物车商品
            String productCodes=req.getParameter("codes");
            this.putShoppingCarts(shoppingCarts,productCodes);
            orderInfo.setShoppingCartList(shoppingCarts);

            ret = orderService.generateOrder(orderInfo);
            m.addObject("ret", ret);
            if (ret.getCode().equals(Result.CODE_100)) {
                m.setViewName("forward:/views/jsp/center/trade/shoppingcart/c_shopping_cart_list.jsp");
                return m;
            }

            m.setViewName("forward:/views/jsp/center/trade/order/c_order_list.jsp");
        } catch (Exception e) {
            ret.setCodeResult(Result.CODE_100, e.getMessage());
            m.addObject("ret", ret);
            m.setViewName("forward:/views/jsp/center/trade/shoppingcart/c_shopping_cart_list.jsp");

        }
        return m;
    }

    /**
     * 下单接口 ajax 确认订单, 实际调用的确认订单接口2016/5/18
     * @param orderInfo
     * @param req
     * @return
     */
    @RequestMapping(value = "generateOrderAjax.s")
    @ResponseBody
    public Result generateOrderAjax(OrderInfoVO orderInfo, HttpServletRequest req) {
        Result ret = new Result();
        try {
            WebTokenUser tokenUser = getWebTokenUser(req);
            if (tokenUser == null) {
                ret.setCodeResult(Result.CODE_100, "请重新登陆");
                return ret;
            }
            orderInfo.setUser(tokenUser);

            List<EmSShoppingCart> shoppingCarts=new ArrayList<>();
            //选中购物车商品
            String productCodes=req.getParameter("codes");
            this.putShoppingCarts(shoppingCarts,productCodes);
            orderInfo.setShoppingCartList(shoppingCarts);

            ret = orderService.generateOrder(orderInfo);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "系统异常" + e.getMessage());
        }
        return ret;
    }

    /**
     * @Title: cancelOrder
     * @Description: 取消订单
     */
    @RequestMapping(value = "cancelOrder.s")
    @ResponseBody
    public Result cancelOrder(OrderInfoVO vo, HttpServletRequest req) {

        Result ret = new Result();
        try {
            WebTokenUser tokenUser = getWebTokenUser(req);

            if (tokenUser == null) {
                ret.setCodeResult(Result.CODE_100, "请重新登陆");
                return ret;
            }
            vo.setUser(tokenUser);
            ret = orderService.cancelOrder(vo);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "系统异常" + e.getMessage());
        }
        return ret;
    }

    @RequestMapping(value = "chooseOrderFeeType.s")
    @ResponseBody
    public Result chooseOrderFeeType(HttpServletRequest req) {

        Result ret = new Result();
        try {
            String orderCode = req.getParameter("orderCode");
            String orderType = req.getParameter("orderType");
            if ("".equals(orderType) || "".equals(orderCode)) {
                ret.setCodeResult(Result.CODE_100, "单据类型选择不合法!");
                return ret;
            }
            ret = orderService.chooseOrderFeeType(orderCode, Integer.parseInt(orderType));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "系统异常" + e.getMessage());
        }
        return ret;
    }

    @RequestMapping(value = "downloadOrderBatchZip.s")
    @ResponseBody
    public Result downloadOrderBatchZip(String orderCode) {
        Result ret = new Result();
        try {

            ret = orderService.downloadOrderBatchZip(orderCode);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return ret;

    }

    /**
     * @Title: confirmOrder
     * @Description: 确认收货
     */
    @RequestMapping(value = "confirmOrder.s")
    @ResponseBody
    public Result confirmOrder(EmSOrder emSOrder, HttpServletRequest req) {

        Result ret = new Result();
        try {
            WebTokenUser tokenUser = getWebTokenUser(req);

            if (tokenUser == null) {
                ret.setCodeResult(Result.CODE_100, "请重新登陆");
                return ret;
            }
            emSOrder.setConfirmUser(tokenUser.getUserId());
            ret = orderService.updateOrderForConfirm(emSOrder);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "系统异常" + e.getMessage());
        }
        return ret;
    }
    

}
